#include "main_page.h"
#include "ui_main_page.h"

#include "weatherdata.h"
#include "weathertool.h"


#include<QAction>
#include <QContextMenuEvent>
#include <QNetworkRequest> // 用于构建网络请求
#include <QUrl> // 用于处理URL
#include <QDebug> // 用于打印调试信息
#include<QMessageBox>
#include<QJsonArray>
#include<QJsonDocument>
#include<QJsonObject>
#include<QMessageBox>

#include <QLabel>
#include <QPixmap>

#include <QPainter>
#include <QPen>



main_page::main_page(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::main_page)
{
    ui->setupUi(this);
    //main_page* main_pagge=new main_page();
    this->setStyleSheet("QLabel { color: white; }");
    //this->setStyleSheet("background-image: url(:/res/Background.png );");

    //构建右键菜单
    mExitMenu = new QMenu(this);
    mExitAct = new QAction();
    mExitAct->setText("退出");
    mExitAct->setIcon(QIcon(":/res/close.png"));
    mExitMenu->addAction(mExitAct);
    connect(mExitAct,&QAction::triggered,this,[=](){qApp->exit(0);});

    this->setWindowTitle("工业生产检测系统");
    ui->leCity->setPlaceholderText("城市查询");


    ui->lblPM25Title->setText("PM2.5");
    ui->lblQualityTiTle->setText("空气质量");
    ui->lblShiDuTitle->setText("湿度");

//    this->setStyleSheet("border-image:url(:/res/Background.png)");




    QPixmap pixmap(":/res/WindDirection.png");
    ui->lblWindIcon->setPixmap(pixmap);
    ui->lblWindIcon->setScaledContents(true);

    ui->lblShiDuIcon->setPixmap(QPixmap(":/res/Humidity.png"));
    ui->lblShiDuIcon->setScaledContents(true);

    QPixmap pixmap2(":/res/PM2.5.png");
    ui->lblPM25Icon->setPixmap(pixmap2);
    ui->lblPM25Icon->setScaledContents(true);

    ui->lblQualityIcon->setPixmap(QPixmap(":/res/AirQuality.png"));
    ui->lblQualityIcon->setScaledContents(true);




    //UI初始化 初始化列表
    //将 控件 放到 数组 里，方便使用 循环 进行处理
    //星期和日期
    mWeekList << ui->lblWeek0 << ui->lblWeek1 << ui->lblWeek2<< ui->lblWeek3<< ui->lblWeek4<< ui->lblWeek5;
    mDateList << ui->lblDate0 << ui->lblDate1 << ui->lblDate2<< ui->lblDate3<< ui->lblDate4<< ui->lblDate5;




    //天气和天气图标
    mTypeList << ui->lblType0<< ui->lblType1<< ui->lblType2<< ui->lblType3<< ui->lblType4<< ui->lblType5;

    mTypeIconList << ui->lblTypeIcon0 << ui->lblTypeIcon1 << ui->lblTypeIcon2 << ui->lblTypeIcon3 << ui->lblTypeIcon4 << ui->lblTypeIcon5;

    //天气指数
    mAqiList << ui->lblQuality0 << ui->lblQuality1 << ui->lblQuality2 << ui->lblQuality3 << ui->lblQuality4 << ui->lblQuality5;

    //风向和风力
    mFxList << ui->lblFx0 << ui->lblFx1 << ui->lblFx2 << ui->lblFx3 << ui->lblFx4 << ui->lblFx5;
    mFlList << ui->lblFl0 << ui->lblFl1 << ui->lblFl2 << ui->lblFl3 << ui->lblFl4 << ui->lblFl5;

    mTypeMap.insert("暴雪",":/res/BaoXue.png");
    mTypeMap.insert("多云",":/res/DuoYun.png");
    mTypeMap.insert("晴",":/res/Qing.png");
    mTypeMap.insert("小雨",":/res/XiaoYv.png");
    mTypeMap.insert("中雨",":/res/ZhongYv.png");
    mTypeMap.insert("大雨",":/res/DaYv.png");
    mTypeMap.insert("阴",":/res/Yin.png");



    mNetAccessManager = new QNetworkAccessManager(this);
    connect(mNetAccessManager,&QNetworkAccessManager::finished,this,&main_page::onReplied);

    //直接在构造中，请求天气数据
    //101010100
//    getWeatherInfo("101280101");
    getWeatherInfo("南京");

    //5.给标签添加事件过滤器
    //参数指定为this，也就是当前窗口对象 MainWindow
    ui->lblHighCurve->installEventFilter(this);
    ui->lblLowCurve->installEventFilter(this);


}

main_page::~main_page()
{
    delete ui;
}


void  main_page::getWeatherInfo(QString cityName){

    QString cityCode = WeatherTool::getCityCode(cityName);

    if(cityCode.isEmpty()){
        QMessageBox::warning(this,"天气","请检查输入是否正确",QMessageBox::Ok);
        return;
    }


    QUrl url("http://t.weather.itboy.net/api/weather/city/"+cityCode);

    QNetworkRequest request(url);
    mNetAccessManager->get(request);

    //mNetAccessManager->get(QNetworkRequest(url));

}

void main_page::onReplied(QNetworkReply *reply)
{
    //    qDebug() << "onReplied success";
        int status_code = reply -> attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

        qDebug() << "operation:" << reply->operation();
    qDebug() << "status code:" << status_code;
    qDebug() << "url:" << reply->url();
    qDebug() << "raw header:" << reply->rawHeaderList();

//    if (reply->error() == QNetworkReply::NoError) {
//            // 处理请求成功返回的数据
//            QByteArray data = reply->readAll();
//            // TODO: 处理数据
//        } else {
//            // 处理请求错误
//            qDebug() << "Error: " << reply->errorString();
//        }

    if(reply->error() != QNetworkReply::NoError || status_code !=200){
        qDebug() << reply->errorString().toLatin1().data();
        QMessageBox::warning(this,"天气","请求数据失败",QMessageBox::Ok);
    }else{
        QByteArray byteArray = reply->readAll();
        qDebug() << "read all:" << byteArray.data();
       parseJson(byteArray);
    }

    reply->deleteLater();

}

void main_page::parseJson(QByteArray &byteArray)
{
    QJsonParseError err;
    QJsonDocument doc = QJsonDocument::fromJson(byteArray,&err);
    if(err.error != QJsonParseError::NoError){
        return;
    }

    QJsonObject rootObj = doc.object();
    qDebug() << rootObj.value("message").toString();

    //1.解析日期和城市
    mToday.date = rootObj.value("date").toString();
    mToday.city = rootObj.value("cityInfo").toObject().value("city").toString();
    qDebug() << mToday.date << mToday.city;

    //2.解析yesterday
    QJsonObject objData = rootObj.value("data").toObject();

    QJsonObject objYesterday = objData.value("yesterday").toObject();
    mDay[0].week = objYesterday.value("week").toString();
    mDay[0].date = objYesterday.value("ymd").toString();

    mDay[0].type = objYesterday.value("type").toString();

    qDebug() << mDay[0].week << mDay[0].date <<  mDay[0].type;

    QString s1,s2;

    s1 = objYesterday.value("high").toString().split(" ").at(1);
    s1.chop(1);
    mDay[0].high = s1.toInt();

    //left()函数的作用是截取字符串的左侧部分，但是它不会修改原始字符串，而是返回一个新的字符串
    s2 = objYesterday.value("low").toString().split(" ").at(1);
    s2 = s2.left(s2.length()-1);
    mDay[0].low = s2.toInt();
    qDebug() <<s1<<s2;
    qDebug() <<mDay[0].high<<mDay[0].low;


    //风向风力
    mDay[0].fx = objYesterday.value("fx").toString();
    mDay[0].fl = objYesterday.value("fl").toString();

    //污染指数
    mDay[0].aqi = objYesterday.value("aqi").toDouble();

    qDebug() <<mDay[0].fx<<mDay[0].fl<<mDay[0].aqi;


    //3.解析forecast中的5天的数据
    QJsonArray forecastArr = objData.value("forecast").toArray();

    int i;
    for(i=0;i<5;i++){
        QJsonObject objForecast = forecastArr[i].toObject();
        mDay[i+1].week = objForecast.value("week").toString();
        mDay[i+1].date = objForecast.value("date").toString();

        mDay[i+1].type = objForecast.value("type").toString();


        //高低温
        QString s;
        s = objForecast.value("high").toString().split(" ").at(1);
        s = s.left(s.length() - 1);
        mDay[i+1].high = s.toInt();

        s = objForecast.value("low").toString().split(" ").at(1);
        s = s.left(s.length() - 1);
        mDay[i+1].low = s.toInt();

        //风向风力
        mDay[i+1].fx = objForecast.value("fx").toString();
        mDay[i+1].fl = objForecast.value("fl").toString();

         //污染指数
        mDay[i+1].aqi = objForecast.value("aqi").toDouble();

qDebug() << mDay[i+1].week<< mDay[i+1].date<< mDay[i+1].high<< mDay[i+1].low<< mDay[i+1].fx<< mDay[i+1].fl<< mDay[i+1].aqi;
    }

    //4.解析今天的数据
    mToday.ganmao = objData.value("ganmao").toString();

    QString wenduStr = objData.value("wendu").toString();
    mToday.wendu = wenduStr.toDouble();

    mToday.shidu = objData.value("shidu").toString();
    mToday.pm25 = objData.value("pm25").toDouble();
    mToday.quality = objData.value("quality").toString();
  qDebug() <<mToday.ganmao<<mToday.wendu<<mToday.shidu<<mToday.pm25<<mToday.quality;

    //5.forcast中第一个数组元素，也是今天的数据
    mToday.type =mDay[1].type;

    mToday.fx = mDay[1].fx;
    mToday.fl = mDay[1].fl;
    mToday.high=mDay[1].high;
    mToday.low= mDay[1].low;
    qDebug()<<mToday.type<<mToday.fx<<mToday.fl<<mToday.high<<mToday.low;

   //6.更新UI
   //6.1显示文本和图标
    updateUI();

   //6.2绘制温度曲线
    ui->lblHighCurve->update();
    ui->lblLowCurve->update();

}


void main_page::updateUI(){

    //1.更新日期和城市
//  ui->lblDate->setText(mToday.date);
    ui->lblDate->setText(QDateTime::fromString(mToday.date,"yyyyMMdd").toString("yyyy/MM/dd")+" "+mDay[1].week);
    ui->lblCity->setText(mToday.city);
    qDebug()<<mToday.date<<mToday.city;

    //2.更新今天
    ui->lblTypeIcon->setPixmap(mTypeMap[mToday.type]);
    ui->lblTemp->setText(QString::number(mToday.wendu)+ "℃");
    //ui->lblTemp->setText(mToday.type);
    ui->lblLowHigh->setText(QString::number(mToday.low)+"~"+QString::number(mToday.high)+"℃");


    ui->lblGanMao->setText("感冒指数：" + mToday.ganmao);
    ui->lblGanMao->setWordWrap(true);
    ui->lblGanMao->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
    qDebug()<<mToday.ganmao;

    ui->lblWindFx->setText(mToday.fx);
    ui->lblWindFl->setText(mToday.fl);

    ui->lblPM25->setText(QString::number(mToday.pm25));

    ui->lblShiDu->setText(mToday.shidu);
    ui->lblQuality->setText(mToday.quality);


      //3.更新六天
        int i;
        for(i = 0; i < 6; i++) {
            //3.1更新日期和时间
            mWeekList[i]->setText("周" + mDay[i].week.right(1));
            ui->lblWeek0->setText("昨天");
            ui->lblWeek1->setText("今天");
            ui->lblWeek2->setText("明天");

            QStringList ymdList = mDay[i].date.split("-");

            mDateList[i]->setText( mDay[i].date);
            if (ymdList.size() == 3) {
//               mDateList[i]->setText(ymdList[1] + "/" + ymdList[2]);
//                 mDateList[i]->setText( mDay[i].date);
                qDebug() << ymdList[1] + "/" + ymdList[2];
            } else {
                qDebug() << "Invalid date format for mDay[" << i << "].date:" << mDay[i].date;
            }

        //3.2更新天气类型
        mTypeList[i]->setText(mDay[i].type);
        mTypeIconList[i]->setPixmap(mTypeMap[mDay[i].type]);

        //3.3 更新空气质量
        if(mDay[i].aqi >= 0 && mDay[i].aqi <=50){
            mAqiList[i]->setText("优");
            mAqiList[i]->setStyleSheet("background-color: rgb(121,184,0);");
        }else if(mDay[i].aqi >50 &&mDay[i].aqi <=100){
            mAqiList[i]->setText("良");
            mAqiList[i]->setStyleSheet("background-color:rgb(255,187,23)");
        }else if(mDay[i].aqi >100 &&mDay[i].aqi <=150){
            mAqiList[i]->setText("轻度");
            mAqiList[i]->setStyleSheet("background-color:rgb(255,87,97)");
        }else if(mDay[i].aqi >150 &&mDay[i].aqi <=200){
            mAqiList[i]->setText("中度");
            mAqiList[i]->setStyleSheet("background-color:rgb(235,17,27)");
        }else if(mDay[i].aqi >200 &&mDay[i].aqi <=250){
            mAqiList[i]->setText("重度");
            mAqiList[i]->setStyleSheet("background-color:rgb(170,0,0)");
        }else {
            mAqiList[i]->setText("严重");
            mAqiList[i]->setStyleSheet("background-color:rgb(110，0,0)");
        }

        //3.4 更新风力、风向
        mFxList[i]->setText(mDay[i].fx);
        mFxList[i]->setStyleSheet("background-color: rgb(61,107,143);");
        mFlList[i]->setText(mDay[i].fl);
        mFlList[i]->setStyleSheet("background-color: rgb(61,107,143);");

        }


}


bool main_page::eventFilter(QObject *watched, QEvent *event)
{
    if(watched == ui-> lblHighCurve && event->type() == QEvent::Paint){
        paintHighCurve();
    }

    if(watched == ui->lblLowCurve && event->type() == QEvent::Paint){
        paintLowCurve();
    }

    return QWidget::eventFilter(watched,event);
}

void main_page::paintHighCurve()
{
    QPainter painter(ui->lblHighCurve);

    //抗锯齿
    painter.setRenderHint(QPainter::Antialiasing,true);

    //1.获取x坐标
    int pointX[6] = {0};
    for(int i = 0; i < 6; i++){
        pointX[i] = mWeekList[i]->pos().x() + mWeekList[i]->width()/2;
    }

    //2.获取y坐标

    int tempSum = 0;
    int tempAverage = 0;
    for(int i = 0; i < 6; i++){
        tempSum += mDay[i].high;
    }
    tempAverage = tempSum / 6; //最高温的平均值

    //计算 y轴坐标
//    int pointY[6] = {0};
    int* pointY = new int[6];
    int yCenter = ui->lblHighCurve->height()/2;
    for(int i = 0; i<6; i++){
        pointY[i] = yCenter - ((mDay[i].high - tempAverage) * 3);
    }

    //3.开始绘制
    //3.1初始化画笔相关
    QPen pen = painter.pen();
    pen.setWidth(1);                //设置画笔的宽度
    pen.setColor(QColor(255,170,0));//设置画笔的颜色

    painter.setPen(pen);
    painter.setBrush(QColor(255,170,0));

    //3.2画点、写文本
    for(int i = 0; i<6; i++){
        //显示点
        painter.drawEllipse(QPoint(pointX[i],pointY[i]),3,3);

        //显示温度文本
        painter.drawText(pointX[i]-12, pointY[i]-12, QString::number(mDay[i].high) + "°");
    }

    //3.3绘制曲线
    for(int i=0;i < 5;i++){

        if(i==0){
            pen.setStyle(Qt::DotLine);//虚线
            painter.setPen(pen);
        }else{
            pen.setStyle(Qt::SolidLine);//实线
            painter.setPen(pen);
        }
        painter.drawLine(pointX[i],pointY[i],pointX[i+1],pointY[i+1]);
    }

    delete[] pointY;
}

void main_page::paintLowCurve()
{
    QPainter painter(ui->lblLowCurve);

    //抗锯齿
    painter.setRenderHint(QPainter::Antialiasing,true);

    //1.获取x坐标
    int pointX[6] = {0};
    for(int i = 0; i < 6; i++){
        pointX[i] = mWeekList[i]->pos().x() + mWeekList[i]->width()/2;
    }

    //2.获取y坐标

    int tempSum = 0;
    int tempAverage = 0;
    for(int i = 0; i < 6; i++){
        tempSum += mDay[i].low;
    }
    tempAverage = tempSum / 6; //最高温的平均值

    //计算 y轴坐标
//    int pointY[6] = {0};
    int* pointY = new int[6];
    int yCenter = ui->lblLowCurve->height()/2;
    for(int i = 0; i<6; i++){
        pointY[i] = yCenter - ((mDay[i].low - tempAverage) * 3);
    }

    //3.开始绘制
    //3.1初始化画笔相关
    QPen pen = painter.pen();
    pen.setWidth(1);                //设置画笔的宽度
    pen.setColor(QColor(0,255,255));//设置画笔的颜色

    painter.setPen(pen);
    painter.setBrush(QColor(0,255,255));

    //3.2画点、写文本
    for(int i = 0; i<6; i++){
        //显示点
        painter.drawEllipse(QPoint(pointX[i],pointY[i]),3,3);

        //显示温度文本
        painter.drawText(pointX[i]-12, pointY[i]-12, QString::number(mDay[i].high) + "°");
    }

    //3.3绘制曲线
    for(int i=0;i < 5;i++){

        if(i==0){
            pen.setStyle(Qt::DotLine);//虚线
            painter.setPen(pen);
        }else{
            pen.setStyle(Qt::SolidLine);//实线
            painter.setPen(pen);
        }
        painter.drawLine(pointX[i],pointY[i],pointX[i+1],pointY[i+1]);
    }
    delete[] pointY;
}

void main_page::keyReleaseEvent(QKeyEvent *event){
    switch (event->key()) {
    case Qt::Key_Return:
        on_btnSearch_clicked();
        break;
    case Qt::Key_Enter:
        on_btnSearch_clicked();
        break;
    default:
        break;
    }
}



//弹出 右键菜单
void main_page::contextMenuEvent(QContextMenuEvent *event)
{
    //弹出 右键菜单
    mExitMenu->exec(QCursor::pos());

    event->accept();
}

//重写鼠标事件
void main_page::mousePressEvent(QMouseEvent *event)
{
//    qDebug() << "窗口左上角："<< this->pos() << ",鼠标坐标点"<< event ->globalPos();

    mOffset = event->globalPos() - this->pos();
}
void main_page::mouseMoveEvent(QMouseEvent *event)
{
    this->move(event->globalPos() - mOffset);
}

void main_page::on_btnSearch_clicked()
{
    QString cityName = ui->leCity->text();
    getWeatherInfo(cityName);
}

void main_page::on_pBtn_back_clicked()
{
    this->hide();
    emit backToMainPage();
}
